<template>
  <div>
    <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
      :before-close="handleClose" destroy-on-close draggable>
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>人员派遣{{ ruleForm.id ? '编辑' : '新增' }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close">
            <CircleCloseFilled color="#fff" />
          </el-icon>
        </div>
      </template>
      <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
        <!-- 基本信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>基本信息</BaseHead>
          <div class="p-[10px]">

            <el-row :gutter="20">

              <el-col :span="12">
                <el-form-item label="课题名称" prop="name">
                  <el-input placeholder="请输入课题名称" v-model="ruleForm.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="研究类别" prop="researchTypeId">
                  <el-radio-group v-model="ruleForm.researchTypeId">
                    <el-radio value="1" label="国内" size="large"></el-radio>
                    <el-radio value="2" label="国外" size="large"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="派遣人员姓名" prop="dispatchName">
                  <el-select v-model="ruleForm.dispatchName" :disabled="Cookies.get('role-key') == 'biz_kyry'"
                    @change="selectAuthor" filterable remote reserve-keyword placeholder="请输入关键字检索"
                    :remote-method="remoteMethod" :loading="loading">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="unitId">
                  <el-select v-model="ruleForm.unitId" placeholder="请选择所属单位"
                    :disabled="Cookies.get('role-key') == 'biz_kyry'" clearable>
                    <el-option v-for="item in zcgsdwList" :key="item.codeColumn" :label="item.valueColumn"
                      :value="item.codeColumn" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开始日期" prop="beginDate">
                  <el-date-picker v-model="ruleForm.beginDate" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                    :disabled-date="disableAfterEndDate" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束日期" prop="endDate">
                  <el-date-picker v-model="ruleForm.endDate" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                    :disabled-date="disableBeforeStartDate" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="ruleForm.note" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="submitForm(ruleFormRef, '-1')" v-if="ruleForm.checkstatus != '2'"
              :loading="btnLoading">暂存</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="checkEditButton()" :loading="btnLoading">{{
      Cookies.get("role-key") ==
        'biz_kyry' ? '提交' : ruleForm.checkstatus == '2' ? '保存' :
        '保存并通过' }}</el-button>
            <el-button type="primary" @click="initData()">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { getpersonnelDispatchAdd, getpersonnelDispatchUpdate } from "@/api/achievement/xsjl"
import { getPersonDetails } from "@/api/achievement/common.js"
import { ElMessage, ElMessageBox } from "element-plus";
import Cookies from 'js-cookie'
import useUserStore from "@/store/modules/user";

const dialogVisible = defineModel();
const props = defineProps({
  hylxList: Array,
  zcgsdwList: Array,
})
const ruleForm = reactive({
  name: '',
  researchTypeId: '1',
  unitId: '',
  dispatchName: '',
  dispatchId: '',
  beginDate: '',
  endDate: '',
  note: '',
})
const rules = reactive({
  name: [
    { required: true, message: '课题名称', trigger: 'blur' },
  ],
  dispatchName: [
    { required: true, message: '请输入派遣人员姓名', trigger: 'blur' },
  ],
  researchTypeId: [
    {
      required: true,
      message: '请选择会议类型',
      trigger: 'change',
    },
  ],
  unitId: [
    {
      required: true,
      message: '请选择所属单位',
      trigger: 'change',
    },
  ],
  beginDate: [
    {
      required: true,
      message: '请选择开始日期',
      trigger: 'change',
    },
  ],
  endDate: [
    {
      required: true,
      message: '请选择结束日期',
      trigger: 'change',
    },
  ],
})

const btnLoading = ref(false)
const ruleFormRef = ref()
const submitForm = async (formEl, i) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      btnLoading.value = true;
      let params = {
        ...ruleForm,
      }
      params.submitType = i ? i : Cookies.get("role-key") == 'biz_kyry' ? '1' : '2'
      // if (i == '-1') {
      //   if (!ruleForm.id || Cookies.get("role-key") == 'biz_kyry') {
      //   } else {
      //     params.submitType = params.checkstatus
      //   }
      // }
      console.log(params, 'params')
      if (params.id) {
        getpersonnelDispatchUpdate(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      } else {
        getpersonnelDispatchAdd(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const options = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    let pamrs = {
      name: query
    }
    getPersonDetails(pamrs).then(res => {
      if (res.code == 200) {
        let arr = res.data;
        arr.map(item => {
          item.value = item.name + ' ' + item.account + ' ' + item.unitName;
          item.label = item.name + ' ' + item.account + ' ' + item.unitName;
        })
        options.value = arr
        loading.value = false
      }
    })
  } else {
    options.value = []
  }
}
// unit_id
const selectAuthor = (e, index, row) => {
  let userInfo = options.value.find(item => item.value == e)
  ruleForm.dispatchId = userInfo.id
  ruleForm.dispatchName = userInfo.name
}

const emit = defineEmits(['callBack']);
const handleClose = (done) => {
  Object.assign(ruleForm, {
    name: '',
    researchTypeId: '1',
    unitId: '',
    dispatchName: '',
    dispatchId: '',
    beginDate: '',
    endDate: '',
    note: '',
  })
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  emit('callBack', "")
  done()
}

const initData = () => {
  Object.assign(ruleForm, {
    name: '',
    researchTypeId: '1',
    unitId: '',
    dispatchName: '',
    dispatchId: '',
    beginDate: '',
    endDate: '',
    note: '',
  })
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  dialogVisible.value = false
}

const getRuleForm = (i) => {
  for (const key in i) {
    ruleForm[key] = i[key];
  }
  console.log(ruleForm, 'ruleForm')
}

const checkEditButton = () => {
  if (ruleForm.id) {
    if (Cookies.get("role-key") == 'biz_kyry') {
      return true
    } else if (Cookies.get("role-key") == 'biz_kyms') {
      if (ruleForm.checkstatus == '1' && ruleForm.isAuditor) {
        return true
      } else {
        return false
      }
    } else if (Cookies.get("role-key") == 'biz_kycgly') {
      if (ruleForm.checkstatus == '1') {
        return ruleForm.isAuditor ? true : false
      } else {
        return true
      }
    } else {
      return false
    }

  } else {
    return true
  }
}


const userStore = useUserStore();

const getKyryInfo = () => {
  if (Cookies.get("role-key") == 'biz_kyry') {
    let pamrs = {
      account: userStore.account
    }
    let kyryInfoArr = []
    getPersonDetails(pamrs).then(res => {
      if (res.code == 200) {
        kyryInfoArr = res.data.filter((item) => {
          return item.name == userStore.nickName
        });
        if (kyryInfoArr && kyryInfoArr.length) {
          ruleForm.dispatchName = kyryInfoArr[0].name
          ruleForm.dispatchId = kyryInfoArr[0].id
          ruleForm.unitId = kyryInfoArr[0].unitId

        }
      }
    })
  }
}

defineExpose({
  getRuleForm,
  getKyryInfo
})


const disableBeforeStartDate = (time) => {
  if (!ruleForm.beginDate) return false; // 如果没有开始日期，则不限制结束日期
  return time.getTime() <= new Date(ruleForm.beginDate).getTime(); // 禁用所有在开始日期之前的日期
}

const disableAfterEndDate = (time) => {
  if (!ruleForm.endDate) return false; // 如果没有开始日期，则不限制结束日期
  return time.getTime() >= new Date(ruleForm.endDate).getTime(); // 禁用所有在开始日期之前的日期
}


</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>
